stuffbyax
stuffbyax

Reputation: 31

Is there any way in Python to create an immutable shallow copy of any object?

In my specific case, I would like to pass a dictionary that contains lists that I don't want exposed without having to make a time-consuming deep copy. But, I am also wondering this just in general as well.

In my case I am trying to pass an object to this one:

dictionary = 
{'x': 
    {
    0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, 
    'y':
{
    0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
} 
.
.
.

Upvotes: 0

Views: 175

Answers (1)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9714

without converting to an immutable type (for example list to tuple) you can't magically convert an object to be immutable.

Immutability is not a flag or something simple like that - it is about the behaviour of the methods on the object.

You could create your own custom container that has a mutable toggle (and which effectively disables some methods when mutable is on), but Python doesn't offer anything like that out of the box.

Upvotes: 2

Related Questions