简体   繁体   中英

Is there a name for this kind of variable stomping bug?

I solved a bug recently where (in Python code) a dictionary variable was initialized outside the loop, then modified and assigned to another dictionary within the loop. The expectation was that a deep copy of the variable was being assigned to the dictionary, but really it was the same variable being passed in over and over. The end result was that the dictionary contained a bunch of repeated dictionaries within it, instead of unique dictionaries for each iteration of the loop.

Something like this:

d = []
a = {"key": "value"}
for x in range(5):
    a["key2"] = "value" + str(x)
    d.append({"results": a})

Where the proper behavior is something more like this

d = []
for x in range(5):
    a = {"key": "value", "key2": "value" + str(x)}
    d.append({"results": a})

Going to write a changelog message for this fix, I was wondering if there was a proper term for this kind of bug? The best I could come up with was "variable stomping" but I believe there's more descriptive.

I would use a line like

Create a new dictionary at each iteration to prevent mutating template

This makes it clear what the original issue is and how it's solved - as for naming, the word is mutating !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM