Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically readdress all variables referring to an object

Tags:

python

Suppose I have in python this object

class Foo:  
    def __init__(self, val):
        self.val = val

and these two variables

a=Foo(5)
b=a

both b and a refer to the same instance of Foo(), so any modification to the attribute .val will be seen equally and synchronized as a.val and b.val.

>>> b.val
5
>>> b.val=3
>>> a.val
3

Now suppose I want to say a=Foo(7). This will create another instance of Foo, so now a and b are independent.

My question is: is there a way to have b readdressed automatically to the new Foo() instance, without using an intermediate proxy object? It's clearly not possible with the method I presented, but maybe there's some magic I am not aware of.

like image 913
Stefano Borini Avatar asked Dec 29 '22 08:12

Stefano Borini


1 Answers

As Aaron points out, there may be very hacky and fragile solutions but there is likely nothing that would be guaranteed to work across all Python implementations (e.g. CPython, IronPython, Jython, PyPy, etc). But why would one realistically want to do something that is so contrary to the design and idiomatic use of the language when there are simple idiomatic solutions available? Calling a class object typically returns an instance object. Names are bound to that object. Rather than trying to fight the language by coming up with hacks to track down references to objects in order to update bindings, the natural thing would be to design a mutable instance object, if necessary using a simple wrapper around an existing class.

like image 100
Ned Deily Avatar answered Feb 15 '23 05:02

Ned Deily