How can I copy a namedtuple or all objects within a namedtuple?

So this should be simple (sorry if it was asked before): I have a namedtuple that saves a bunch of results. Suppose this is:

init_results = (result1 = collect(1:10), result2 = collect(11:20))

How can I copy init_results?

# This assigns, but doesn't copy 
update_results = init_results 
update_results.result1[5] = 0
init_results.result1[5] # should return 5, not 0 

# Also broadcasting doesn't work
update_results .= init_results # Gives ArgumentError

Maybe there is something fundamentally wrong with writing code like this, in which case someone can maybe explain this to me. In my case, I have functions that save and update many different objects as results. It seems very practical to let these functions only take as input the namedtuple (instead of specifying all objects). Of course, the namedtuple is immutable, only the content within objects/entries should change.

The function you want is deepcopy()… (copy() works if the thing you’re copying aren’t nested containers inside containers).

I can recommend this blog post for a more thorough discussion. The short version is, when you do update_results = init_results in Julia, you’re just assigning a new name to the exact same object. So when you change one, the other variable points to the same, now changed, thing.

Great, I didn’t know deepcopy(). This works, thanks! Maybe you can amend your answer, since copy() doesn’t work in the example given. Then I can accept the solution.


I should probably mention that if your code is performance critical, doing a copy on every iteration will do a lot of allocating, which can be bad for performance. If you run into this, another post with more details about what you’re doing will get you a lot of really great help from people more knowledgeable than me to speed things up. But one thing I can suggest if you don’t need to save intermediate results is to just make one copy, then update that copy as you did above, since changing elements of a vector is usually much faster than making a new vector.

1 Like

Thanks! This is not important in my case. This is the outer loop in my algorithm, which has very few total iterations + objects are not so big. But will keep this in mind for other problems.

1 Like