A Bug in Plain Sight

Andrew
1 min readJul 31, 2020

--

Recently I came across some code like this:

And the output I got was:

[{“Foo”: “Bar 4”}, {“Foo”: “Bar 4”}, {“Foo”: “Bar 4”}, {“Foo”: “Bar 4”}, {“Foo”: “Bar 4”}]

Certainly this is wrong, and it’s probably quite obvious where the bug is. But for some reason, me from 2 weeks ago couldn’t figure it out, and it took a few searches on StackOverflow to realize what was the problem.

Of course, the bug is because item is defined outside of the for loop, and so the same reference was being updated and appended to the items array multiple times!

In my defence, I’m new to Python and I was coming from doing Go programming just prior to this. By comparison, the following snippet in Go produces the correct results:

--

--

No responses yet