tags:

views:

50

answers:

2

I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem.

import copy

class Obj(object):
    def __init__(self, name):
        self.name = name

def one(o):
    print("1: o.name:", o.name) # "foo"
    obackup = copy.deepcopy(o) 
    o.name = "bar"
    print("2: o.name:", o.name) # "bar"
    print("3: obackup.name:", obackup.name) # "foo"
    o = obackup
    print("4: o.name:", o.name) # "foo"

def two(o):
    print("5: o.name:", o.name) # "bar"!

def main():
    o = Obj("foo")
    one(o)
    two(o)

main()

My guess is that o is being overwritten somehow as a local variable to the function one(). But I have no idea how to fix that.

A: 

o is a local variable to the one() so this problem cannot be fixed elegantly. But you could use some reference/pointer which you pass to the one() and two().

http://stackoverflow.com/questions/1145722/simulating-pointers-in-python

phadej
Thanks. It's good to know that there is no easy fix. I've fixed it now by having all relevant functions return the object.
Skyler
It would be much better to restructure the code (as mentioned, returning the object works well) than to try to simulate pointers.
Aaron Gallagher
+2  A: 

Forget that the copy module exists, it almost never is needed and often produces surprising results.

As soon as you say o = obackup in one() you have created a new binding for the formal argument which then goes out of scope after print('4...

msw