0

I am not sure if this makes any sense in python, but consider I have two variables x and y:

x = 1
y = x

Now, at a later time when I change x, I want y to see this change. that is if I do

x = 2

I want y to be 2 also. Is there a way to do reference(x) = 2, so that all variables that were assigned to x will see this change?

One way to make this work is to use lists for everything as described here. This would work if I had defined x as list, so if

x = [1]
y = x

then, doing x.clear() and x.append(val) for val in new_list would work, and y will change according to the new list.

But I would like to do it for any type, because otherwise I will need to revisit most of my codebase. Is there a mutable type so I don't have to redefine all my y's to be x[0].

Any suggestion is appreciated.

7
  • 2
    I don't understand why you would really want this semantic. Are you refactoring code from another language or something? Commented Feb 28, 2018 at 2:38
  • To put it in context, I have a PyQt tableView where its model has some data. Now, the model's data (type or value) might be changed by the user at any time. I have threads running in the background which use the table's model data from the program start. If a user changes the data, I would rather it be reflected automatically in the other threads and classes without rereading the model. Commented Feb 28, 2018 at 2:42
  • I don't understand you problem that much. You means the y=copy.deepcopy(x) Commented Feb 28, 2018 at 2:44
  • Possible duplicate of Passing an integer by reference in Python Commented Feb 28, 2018 at 3:03
  • @damores not really... I mentioned that answer as possible solution, but i was looking for something different. I suppose the lazy way out I am asking for is just not possible. Commented Feb 28, 2018 at 3:08

1 Answer 1

4

Perhaps make a small wrapper class for your values? The object containing the value is then passed "by reference".

class Wrapper:
    def __init__(self, value):
        self.value = value

x = Wrapper(5)
y = x

print(x.value, y.value)
x.value = 3
print(x.value, y.value)

Output:

5 5
3 3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.