Search code examples
pythonstaticstatic-variables

Python - does deepcopy() creates another copy of Class/Static variables in memory?


This is almost a repost of another question that I made that wasn't very clear.

import copy

class Obj:
    a = 3

    def __init__(self, n: int):
        self.b = n

obj1 = Obj(10)

obj2 = copy.deepcopy(obj1)

I understand that obj1.b and obj2.b are completely different instance variables. And I understand that if I do something like

Obj.a = 20

Both obj1.a and obj2.a would be 20.

Now imagine that sizeof a is N bits. When I do copy a of obj1, does the memory store another a in memory (wasting another N bits) for obj2.a or does obj2.a simply points for the same place in memory as obj1.a?

EDIT: in my program, the class variables are a Set, an int and a tuple and I want to share them across all copies without wasting memory!


Solution

  • As Barmar mentioned in the comments, Python doesn't make copies of immutable objects like numbers, so long as they don't contain mutable objects themselves. If a and b were lists, however,

    class Obj:
        a = [0, 1, 2]
    
        def __init__(self, n: list):
            self.b = n
    
    obj1 = Obj([10, 20, 30])
    
    obj2 = copy.deepcopy(obj1)
    
    print(hex(id(obj1)), hex(id(obj1.a)), hex(id(obj1.b)))
    # Output: 0x1aa036cd7c8 0x1aa03670ec8 0x1aa036eddc8
    print(hex(id(obj2)), hex(id(obj2.a)), hex(id(obj2.b)))
    # Output: 0x1aa036db5c8 0x1aa03670ec8 0x1aa036cf308
    

    More tests:

    obj2.a[0] = 100
    print(obj1.a)
    # Output: [100, 1, 2]
    

    So, to answer your question: obj1.a and obj2.a share memory. obj1.b and obj2.b don't.