Is there a way to force modification of the binded object instead of rebind to a new object?

When you have a variable that points to a mutable object and you use the equal operator, Julia will simply rebind that variable to the new object.

For example, in the following snippet, the objects binded by a and b do not actually change because the variable i pointing to the object pointed by a (or b in the second loop) is simply reassigned to the new objects:

using DataFrames, DataFramesMeta

a = DataFrame(x =[1,3,5])
b = DataFrame(x = [2,4])
for i in (a,b)
    i = @subset(i, :x .> 2)

In situations where in-place editing is not possible (or not simple), is there a way to tell Julia that what you want is that the object to which the variable i points to (but also a, b and all other variables pointing to the same object) is to be replaced with the new object ?

No, this is not possible to do in the general case. AFAIK, there is no system in Julia which keeps track of the relationship between bindings and objects. For example, if I do

a = 1
b = a

There is nothing in the language semantics that lets me recover that a points to the same object as b. Of course you could check that a === b, but there is no link from a to b such that one can write a function that reassigns a and all the downstream variables that directly or indirectly points to it.

In my opinion, if you feel the need to do this, it probably means you should not have distinct variables at all. For example, in the case above, you could keep a vector of dataframes such that a is the first element and b is the second element, then update the entry in the vector. Everything that points to the vector is then automatically updated.

1 Like