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.

Gerges
  • 6,269
  • 2
  • 22
  • 44
  • 2
    I don't understand why you would really want this semantic. Are you refactoring code from another language or something? – miradulo Feb 28 '18 at 02: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. – Gerges Feb 28 '18 at 02:42
  • I don't understand you problem that much. You means the `y=copy.deepcopy(x)`? – Windyground Feb 28 '18 at 02:44
  • Possible duplicate of [Passing an integer by reference in Python](https://stackoverflow.com/questions/15148496/passing-an-integer-by-reference-in-python) – damores Feb 28 '18 at 03: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. – Gerges Feb 28 '18 at 03:08
  • Just use a dictionary and pass it around. – Klaus D. Feb 28 '18 at 03:58
  • You cannot do this in Python (unless you feel like doing some serious hacking of the interpreter) – juanpa.arrivillaga Feb 28 '18 at 05:11

1 Answers1

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
user19650
  • 153
  • 9